package com.itheima.web.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;

@WebFilter("/*")
public class DemoFilter implements Filter {
    private static final int MAX_COUNT = 5;
    private AtomicInteger filterCount = new AtomicInteger(0);
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        if (filterCount.get()>MAX_COUNT){
            response.sendRedirect("/index.jsp");
        }else {
            chain.doFilter(request, response);
            filterCount.incrementAndGet();
            chain.doFilter(request, response);
            //访问结束，请求个数减1
            filterCount.decrementAndGet();
        }

    }

    public void init(FilterConfig config) throws ServletException {

    }

}